<template>
  <div>
    <el-header >
      <div class="report_header" ref="headerHeight">
        <div class="report_header_left"></div>
        <div style="display: flex;flex-direction: row;justify-content:space-between;width: 100%;">
          <div style="display: flex;flex-direction: row;flex-wrap: wrap;overflow: hidden;height:41px">
            <div class="report_header_date">
              <el-date-picker
                v-model="query.date"
                style="width: 100%"
                value-format="yyyy-MM-dd"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
              />
            </div>
            <div class="report_header_query">
              <el-input v-model="query.name" prefix-icon="el-icon-search" placeholder="请输入名称"  @keyup.enter.native="handleFilter" />
            </div>
            <div class="report_header_query">
              <el-input v-model="query.shortName" prefix-icon="el-icon-search" placeholder="请输入简称"  @keyup.enter.native="handleFilter" />
            </div>
            <div class="report_header_query">
              <el-input v-model="query.phone" prefix-icon="el-icon-search" placeholder="请输入联系电话" @keyup.enter.native="handleFilter" />
            </div>
          </div>
          <div>
          <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" @click="handleFilter">查询</el-button>
          <!-- <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" @click="addClick"
                     >新增</el-button> -->
          </div>
        </div>
      </div>
<!--      <div>-->
<!--        <svg-icon class="primary" :icon-class="$route.meta.icon" />-->
<!--        <span class="primary">{{ $route.meta.title }}</span>-->
<!--      </div>-->
<!--      <div class="header-button-container">-->
<!--        <el-button :icon="searchShow? 'el-icon-close':'el-icon-search'" type="primary" @click="chooseClick">{{ searchShow?'隐藏':'查询' }}</el-button>-->
<!--        <el-button v-permission="['sysMch.add']" icon="el-icon-plus" type="info" style="margin-left: 10px" @click="addClick">新增</el-button>-->
<!--      </div>-->
    </el-header>
    <div class="pd10">

<!--        <div v-show="searchShow" style="margin-bottom: 10px">-->
<!--          <el-date-picker-->
<!--            v-model="query.date"-->
<!--            value-format="yyyy-MM-dd"-->
<!--            type="daterange"-->
<!--            align="right"-->
<!--            unlink-panels-->
<!--            range-separator="至"-->
<!--            start-placeholder="开始日期"-->
<!--            end-placeholder="结束日期"-->
<!--            :picker-options="pickerOptions"-->
<!--          />-->
<!--          <el-input v-model="query.name" prefix-icon="el-icon-search" placeholder="请输入名称" style="width: 170px;" @keyup.enter.native="handleFilter" />-->
<!--          <el-input v-model="query.shortName" prefix-icon="el-icon-search" placeholder="请输入简称" style="width: 170px;" @keyup.enter.native="handleFilter" />-->
<!--          <el-input v-model="query.phone" prefix-icon="el-icon-search" placeholder="请输入联系电话" style="width: 170px;" @keyup.enter.native="handleFilter" />-->
<!--          <el-button style="margin-left: 10px" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>-->
<!--          <el-button icon="el-icon-refresh-right" type="info" style="margin-left: 10px" @click="resetSearch">重置</el-button>-->
<!--        </div>-->

      <el-table
        v-loading="isLoading"
        v-loadMore="[payLoads,'sysMch-list']"
        :data="tableData"
        style="width: 100%;margin-bottom: 20px;"
        row-key="id"
        :height="curHeight"
        border
        stripe
        @sort-change="sortChange"
      >
        <el-table-column
          align="center"
          prop="createDate"
          label="注册时间"

          width="170"
        >
          <template slot-scope="{row}">
            <span style="margin-left: 10px">{{ row.createDate | datetimeFormatter }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="id"
          label="商户ID"

          width="70"
        />
        <el-table-column
          prop="name"
          label="商户名称"
          sortable="custom"
          
        />
        <el-table-column
          align="center"
          label="商户类型"
          prop="mchType"
          sortable="custom"
          width="120"
        >
          <template slot-scope="{row}">
            {{row.mchType | mchTypeFormatter}}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="shortName"
          label="商户简称"
          sortable="custom"
          width="120"
        />
        <el-table-column
          align="center"
          prop="linkman"
          label="联系人"
          sortable="custom"
          width="120"
        />
        <el-table-column
          align="center"
          prop="phone"
          label="电话"
          sortable="custom"
          width="110"
        />
        <el-table-column
          align="center"
          prop="status"
          label="状态"
          sortable="custom"
          width="80"
        >
          <template slot-scope="{row}">
            <el-tag :type="row.status | statusTagFilter">
              {{ row.status | watchStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="地址"
          sortable="custom"
          width="350"
        />
        <el-table-column
          prop="remark"
          label="备注"
          width="350"
        />
        <el-table-column
          label="功能"
          align="center"
          
          fixed="right"
        >
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="详情" placement="top-start">
              <el-button  type="primary" size="mini" @click="details(scope.row)">详情</el-button>
            </el-tooltip>
           <el-tooltip effect="dark" content="菜单选择" placement="top-start">
              <el-button v-permission="['sysMch.edit']" type="primary" size="mini" @click="dialogShow(scope.row)">菜单</el-button>
              <!-- <el-button  type="primary" size="mini" @click="dialogShow(scope.row)">菜单</el-button> -->
            </el-tooltip>
              <el-tooltip effect="dark" content="插件安装" placement="top-start">
              <el-button v-permission="['sysMch.edit']" type="primary" size="mini" @click="pluginClick(scope.row)">插件</el-button>
            </el-tooltip>
            <!-- <el-tooltip v-permission="['sysMch.edit']" effect="dark" content="一键装修" placement="top-start">
              <el-button :disabled="renovationDisabled" type="primary" size="mini" @click="initISVDataFn(scope.row)">装修</el-button>
            </el-tooltip> -->
            <!-- <el-tooltip v-permission="['sysMch.edit']" effect="dark" content="重置密码" placement="top-start">
              <el-button type="primary" size="mini" @click="resetPwd(scope.row)">重置</el-button>
            </el-tooltip>-->
            <el-tooltip  effect="dark" content="商户审核" placement="top-start">
              <el-button :type="scope.row.status == 1?'danger': 'primary'" size="mini" @click="auditClick(scope.row)">{{ scope.row.status | watchStatusBotton }}</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          align="center"
          label="操作"
          width="80"
        >
          <template slot-scope="scope">
            <div style="display: flex;flex-direction: row;justify-content: center">
              <!-- <el-tooltip v-permission="['sysMch.edit']" class="item" effect="dark" content="编辑" placement="top-start">
                <a @click="editClick(scope.row)">
                  <i style="color: #409EFF" class="el-icon-edit" />
                </a>
              </el-tooltip> -->
              <el-tooltip  class="item" effect="dark" content="删除" placement="top-start">
                <a style="margin-left: 10px" @click="delSysMch(scope.row)">
                  <i style="color: #F56C6C" class="el-icon-delete" />
                </a>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize" @pagination="loadSysMch" />
      <menu-dialog ref="menuDialog" @confirm="dialogConfirm" />
    </div>
  </div>
</template>
<style lang="scss" scoped>

  .app {
    background-color: rgba(248, 248, 248, 0.8);
  }

  /deep/.el-header {
    padding: 10px;
    /* height: 100% !important; */
    padding-bottom: 0;
  }

  .report_header {
    width: 100%;
    min-height: 40px;
    box-sizing: border-box;
    background-color: rgba(248, 248, 248, 0.8);
    display: flex;
    align-items: center;
    padding-bottom: 5px;
    position: relative;
    padding-left: 5px;
    padding-right: 5px;
  }
  .report_header_left {
    width: 5px;
    height: 100%;
    background-color: #409EFF;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
  }
  .report_header_date {
    margin-left: 10px;
    width: 250px;
    margin-top: 5px;
  }
  .report_header_query {
    margin-left: 10px;
    width: 180px;
    margin-top: 5px;
  }
  .el-button-group .el-button--medium {
    padding: 10px 10px !important;
    font-size: 14px !important;
    border-radius: 4px!important;
  }

  .menu-wrapper{
    margin: 15px;
  }
</style>
<script>
import loadMore from '@/utils/loadMore.js'
import permission from '@/directive/permission/index.js' // 权限判断指令
import { EventBus } from '@/api/eventBus'
import utils from '../../utils/utils.js'
import { list, del, addOrUpdateMchMenu, getMenus, resetPwd, update, initISVData } from '@/api/sysMch'
import Pagination from '@/components/Pagination'
import MenuDialog from './components/MenuDialog'
export default {
  name: 'SysMchList',
  directives: { permission, loadMore },
  components: { Pagination, MenuDialog },
  filters: {
    mchTypeFormatter (val) {
      if (val == 0) {
        return '运营商'
      } else if (val == 1) {
        return '普通商户'
      } else if (val == 2) {
        return '特约商户'
      } else if (val == 3) {
        return '服务商(ISV)'
      }
    },
    watchStatus(val) {
      if (val == 1) {
        return '启用'
      } else if (val == 2) {
        return '停用'
      } else {
        return '待审'
      }
    },
    watchStatusBotton(val) {
      if (val == 0) {
        return '审核'
      } else if (val == 1) {
        return '停用'
      } else if (val == 2) {
        return '启用'
      }
    },
    statusTagFilter(val) {
      if (val == 1) {
        return 'success'
      } else if (val == 2) {
        return 'info'
      } else {
        return 'warning'
      }
    }
  },
  data() {
    return {
      payLoads: '',
      tableData: [],
      isLoading: true,
      searchShow: false, // 搜索显示
      renovationDisabled: false,
      query: {
        date: [],
        name: '',
        shortName: '',
        phone: ''
      }, // 绑定的搜索值
      keyword: {
        date: [],
        name: '',
        shortName: '',
        phone: ''
      }, // 实际的搜索值
      pickerOptions: {// 时间快捷选择
        shortcuts: [{
          text: '昨天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      pageNum: 1, // 当前页
      pageSize: 10, // 每页显示条目个数
      total: 0, // 总条目数
      direction: '',
      sortField: '',
      mchId: '',
      curHeight: null
    }
  },
  activated() {
    this.payLoads = new Date().getTime()
  },
  created() {
    const _this = this
    this.loadSysMch()
    EventBus.$on('sysMch-add', res => { // 监听新增完毕
      // 更新列表数组
      _this.tableData.splice(0, 0, res)
    })
    EventBus.$on('sysMch-edit', res => { // 监听新增完毕
      // 更新列表数组
      for (var i = 0; i < _this.tableData.length; i++) {
        if (_this.tableData[i].id == res.id) {
          console.log('111')
          _this.tableData[i] = res
        }
      }
    })
  },
  mounted() {
    this.comeIn()
    this.beforeMount()
  },
  methods: {
    details(row){
      console.log(row);
        this.$router.push({
        path: '/sysMch/details',
        query: { id: row.id }
      })

    },
    beforeMount() {
      window.onresize = () => {
        return (() => {
          if (this.queryType == false) {
            var h = document.documentElement.clientHeight || document.body.clientHeight
            this.curHeight = h - 266// 减去页面上固定高度height
          } else {
            var h = document.documentElement.clientHeight || document.body.clientHeight
            this.curHeight = h - 220// 减去页面上固定高度height
          }
        })()
      }
    },
    comeIn() {
      console.log('222')
      var h = document.documentElement.clientHeight || document.body.clientHeight
      this.curHeight = h - 220// 减去页面上固定高度height
    },
    pluginClick(row) {
      this.$router.push({
        path: '/sysPlugin/list',
        query: { mchId: row.id }
      })
    },
    dialogShow(row) {
      console.log('开启菜单选择弹窗')
      this.mchId = row.id
      this.$refs.menuDialog.show(row.id)
    },
    dialogConfirm(menus, callback) {
      const _this = this
      const params = new URLSearchParams()
      params.append('id', this.mchId)
      var list = []
      menus.forEach(function(item) {
        list.push(item.id)
      })
      addOrUpdateMchMenu(params, list).then(response => {
        console.log(response)
        callback(false)
      }).catch(() => {
        callback(false)
      })
    },
    // 搜索
    handleFilter() {
      console.log(this.keyword.date)
      this.keyword = this.query
      this.pageNum = 1
      this.loadSysMch()
    },
    // 重置搜索
    resetSearch() {
      this.query.date = []
      this.query.name = ''
      this.query.shortName = ''
      this.query.phone = ''
      this.keyword = this.query
      this.pageNum = 1
      this.loadSysMch()
    },
    // 表格排序
    sortChange(column) {
      this.sortField = column.prop
      if (column.order == 'ascending') {
        this.direction = 'asc'
      } else {
        this.direction = 'desc'
      }
      this.loadSysMch()
    },
    // 新增
    addClick() {
      this.$router.push({
        path: '/sysMch/add'
      })
    },
    editClick(row) {
      this.$router.push({
        path: '/sysMch/edit',
        query: { id: row.id }
      })
    },
    resetPwd(row) {
      console.log(row)
      this.$confirm('确定要重置密码为用户名吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetPwd(row.id).then(resolve => {
          console.log(resolve)
          this.$message({
            type: 'success',
            message: '重置后密码为用户名!'
          })
        }).catch(error => {
          console.log(error)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消重置'
        })
      })
    },
    delSysMch(row) {
      const _this = this
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(row.id).then(response => {
          console.log(response)
          // 更新列表数组
          _this.tableData.forEach(function(item, index) {
            if (item.id == row.id) {
              _this.tableData.splice(index, 1)
            }
          })
        }).catch(error => {

        })
      }).catch(() => {
      })
    },
    initISVDataFn(row) {
      this.$confirm('此操作将执行一键装修, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = { mchId: row.id }
        initISVData(params).then(res => {
          console.log(res)
          this.$message({ type: 'success', message: '装修成功!' });
          this.renovationDisabled = true
        }).catch(() => {
          this.$message({ type: 'info', message: '装修失败!' });
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消装修'});
      });
    },
    loadSysMch() {
      const _this = this
      const params = new URLSearchParams()
      params.append('startDate', this.keyword.date.length > 0 ? this.keyword.date[0] : '')
      params.append('endDate', this.keyword.date.length > 0 ? this.keyword.date[1] : '')
      params.append('name', this.keyword.name)
      params.append('shortName', this.keyword.shortName)
      params.append('phone', this.keyword.phone)
      params.append('pageNum', this.pageNum)
      params.append('pageSize', this.pageSize)
      params.append('sortField', this.sortField)
      params.append('direction', this.direction)
      _this.isLoading = true
      list(params).then(response => {
        console.log(response)
        _this.total = response.data.total
        _this.tableData = response.data.data
        _this.isLoading = false
      }).catch(error => {
        _this.isLoading = false
      })
    },
    auditClick(row) {
      let form = {
        id: row.id,
        status: 0
      }
      let text = ''
      if (row.status == 0) {
        form.status = 1
        text = '审核通过'
      } else if (row.status == 1) {
        form.status = 2
        text = '停用'
      } else if (row.status == 2) {
        form.status = 1
        text = '启用'
      }
      this.$confirm(`此操作将${text}该商户, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        update(form).then(response => {
          console.log(response)
          this.loadSysMch()
          this.$message({ type: 'success', message: `${text}成功!`});
        }).catch(error => {})
      }).catch(() => {
        this.$message({ type: 'info', message: `已取消${text}`});
      })
    },
    chooseClick() {
      console.log('111')
      this.searchShow = !this.searchShow
      if (this.searchShow == true) {
        var h = document.documentElement.clientHeight || document.body.clientHeight
        this.curHeight = h - 266// 减去页面上固定高度height
      } else {
        var h = document.documentElement.clientHeight || document.body.clientHeight
        this.curHeight = h - 220// 减去页面上固定高度height
      }
    }
  }
}
</script>
